package edu.nju.desserthouse.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nju.edu.desserthouse.model.Vip;

import edu.nju.desserthouse.dao.VipDao;

/**
 * Servlet implementation class LogInServlet
 */
@WebServlet("/login.vip")
public class LogInServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	@EJB
	VipDao vipDao;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LogInServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		execute(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		execute (request, response);
	}
	
	public void execute(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
		
		String account;
		String password;
		
		account = req.getParameter("account");
		password = req.getParameter("password");
		
		Vip vip = vipDao.find("account", account, "password", password);
		
		if(vip != null){
			req.getSession().setAttribute("vip_id",vip.getId());
			req.getSession().setAttribute("vip_account",vip.getAccount());
			req.getSession().setAttribute("vip_balance", vip.getBalance());
			req.getSession().setAttribute("vip_level", vip.getLevel());
			if(vip.getState() == 0){
				resp.sendRedirect("/desserthouseWEB/user/vipwelcome.jsp");
			}else if(vip.getState() == 1){
				resp.sendRedirect("/desserthouseWEB/user/vippaused.jsp");
			}else if(vip.getState() == 2){
				resp.sendRedirect("/desserthouseWEB/user/vipstopped.jsp");
			}else if(vip.getState() == 3){
				resp.sendRedirect("/desserthouseWEB/user/newuser.jsp");
			}
			
		}else{
			System.out.println("Wrong Input!!!");
			resp.sendRedirect("/desserthouseWEB/error/loginerror.jsp");
		}
	}
}
